package com.android1608.administrator.messagedigest;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MainActivity extends AppCompatActivity {
    private String pw = "jindongxiao";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void messageDigest(View view) {
        switch (view.getId()){
            case R.id.md5:
                String md5 = messageDigest("MD5", pw);
                Log.d("flag", "---------->messageDigest: MD5:" +md5);
                break;
            case R.id.sha_1:
                String sha_1 = messageDigest("SHA-1", pw);
                Log.d("flag", "---------->messageDigest: SHA-1:" +sha_1);
                break;
        }
    }

    private String messageDigest(String type, String data) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance(type);
            //调用方法进行运算
            messageDigest.update(data.getBytes());
            byte[] digest = messageDigest.digest();
            //将数据转化
            Log.d("flag", "---------->messageDigest: " +digest.length);
            for (int i = 0; i < digest.length; i++) {
                Log.d("flag", "---------->messageDigest: " +digest[i]);
            }
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < digest.length; i++) {

                int num = digest[i] & 0xFF;
                if (num<=0xF){
                    builder.append(0);
                }
                String result = Integer.toHexString(num);
                builder.append(result);

            }
            return builder.toString();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        return null;
    }
}
